package com.gsm.system.shiro.realm;

import com.gsm.common.entity.ResultCode;
import com.gsm.common.shiro.realm.CustomRealm;
import com.gsm.common.utils.PermissionConstants;
import com.gsm.domain.system.User;
import com.gsm.domain.system.resp.ProfileResult;
import com.gsm.system.service.PermissionService;
import com.gsm.system.service.UserService;
import org.apache.shiro.authc.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: java类作用描述
 * @Author: gaoshengmin
 * @CreateDate: 2020/2/13$ 21:00$
 * @UpdateUser: gaoshengmin
 * @UpdateDate: 2020/2/13$ 21:00$
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
public class UserRealm extends CustomRealm {

    @Autowired
    private UserService userService;
    @Autowired
    private PermissionService permissionService;

    //认证方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1.获取手机号和密码
        UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;
        String mobile = upToken.getUsername();
        //2.查询用户匹配密码
        User user = userService.findByMobile(mobile);
        String password = new String(upToken.getPassword());
        System.out.println(user.getPassword());
        System.out.println(password);
        if (user != null && user.getPassword().equals(password)) {
            //3.构造安全数据
            ProfileResult result = null;
            if ("companyUser".equals(user.getLevel())) {
                result = new ProfileResult(user);
            } else {
                Map map = new HashMap();
                if ("companyAdmin".equals(user.getLevel())) {
                    map.put("enVisible", "1");
                }
                List list = permissionService.findAll(map);
                result = new ProfileResult(user, list);
            }
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(result, user.getPassword(), this.getName());
            return info;
        }
        //返回 null 则会跑出异常 表示用户名和密码不匹配
        return null;
    }
}
